package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //分页查询权限
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        if (queryString == null || queryString.trim().equals("")) {
            queryString = "";
        }
        PageHelper.startPage(currentPage, pageSize);

        Page<Permission> page = permissionDao.findByCondition("%" + queryString.trim() + "%");

        return new PageResult(page.getTotal(), page.getResult());
    }


    //新增权限
    @Override
    public Integer add(Permission permission) throws Exception {
        String name = "";
        String keyword = "";
        if (permission != null) {
            name = permission.getName();
            keyword = permission.getKeyword();
            permission.setCreateDate(DateUtils.parseDate2String(new Date()));
        }
        Integer nameCount = permissionDao.findCountByName(name);
        if (nameCount > 0) {
            throw new RuntimeException("权限名称已存在");
        }
        Integer keywordCount = permissionDao.findCountByKeyword(keyword);
        if (keywordCount > 0) {
            throw new RuntimeException("权限关键字已存在");
        }
        System.out.println(permission);
        return permissionDao.add(permission);
    }
    //编辑权限
    @Override
    public Integer edit(Permission permission) throws Exception {
        Integer count = 0;
        if (permission != null){
            permission.setCreateDate(DateUtils.parseDate2String(new Date()));
            count = permissionDao.edit(permission);
        }
        return count;
    }

    //删除权限
    @Override
    public Integer deleteById(Integer id) {
        Integer count = permissionDao.findRoleByPermissionId(id);
        if (count > 0){
            throw  new RuntimeException("该权限已关联角色");
        }
        return permissionDao.deleteById(id);
    }

    //回显信息
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

}
